package com.atguigu.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.atguigu.app.func.DimAsyncFunction;
import com.atguigu.bean.ChapterPlay;

import com.atguigu.utils.DateFormatUtil;
import com.atguigu.utils.MyClickHouseUtil;
import com.atguigu.utils.MyKafkaUtil;

import com.atguigu.utils.WindowFunctionUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.*;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.AsyncDataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.WindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.concurrent.TimeUnit;


/**
 * ClassName: DWS161_ChapterPlay
 * Package: com.atguigu.app.dws
 * Description:
 *
 * @Author ChenJun(有志男青年)
 * @Create 2023/5/17 18:52
 * @Version 1.0
 */


//数据流：web/app -> 日志文件 -> flume -> Kafka(ODS) -> FlinkApp -> Kafka(DWD) ->FlinkApp ->Clickhouse(DWS)
//程 序: Mock -> 文件 -> flume -> Kafka(ZK) -> BaseLogApp -> Kafka(ZK)->Dws161_ChapterPlayViewWindow ->Clickhouse(ZK)

public class Dws161_ChapterPlayViewWindow_00 {

    public static void main(String[] args) throws Exception {

        //TODO 1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

//        env.enableCheckpointing(3000L, CheckpointingMode.EXACTLY_ONCE);
//        env.getCheckpointConfig().setCheckpointTimeout(60 * 1000L);
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000L);
//        env.getCheckpointConfig().enableExternalizedCheckpoints(
//                CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION
//        );
//        env.setRestartStrategy(RestartStrategies.failureRateRestart(
//                10, Time.of(1L, TimeUnit.DAYS), Time.of(3L, TimeUnit.MINUTES)
//        ));
//        env.setStateBackend(new HashMapStateBackend());
//        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/ck");
//        System.setProperty("HADOOP_USER_NAME", "atguigu");


        //value={"common":{"sc":"1","ar":"33","uid":"1497","os":"Android 11.0","ch":"wandoujia","is_new":"0","md":"Xiaomi Mix2 ","mid":"mid_93","vc":"v2.1.111","ba":"Xiaomi","sid":"1d7455ef-4d64-46d4-b72e-9ae734f914ec"},"appVideo":{"play_sec":30,"position_sec":240,"video_id":"3716"},"ts":1684322854453}

        //TODO 2.使用FlinkSQL方式读取 DWD层 appvideo主题数据,同时提取时间戳生成WaterMark
        DataStreamSource<String> kafkaDS = env.fromSource(MyKafkaUtil.getKafkaSource("dwd_traffic_video_play",
                        "chenjunjun"),  WatermarkStrategy.noWatermarks(), "kafkaDS");


        //TODO 3.转换为Json对象
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String value, Collector<JSONObject> out) throws Exception {
//                if (value != null) {
//                    try {
                        out.collect(JSON.parseObject(value));
//                    } catch (Exception e) {
//                        System.out.println("脏数据："+value);
//                    }
//                }
            }
        });
        jsonObjDS.print("jsonObjDS-->");

        //4.提取时间戳
        SingleOutputStreamOperator<JSONObject> jsonObjDSWithWMDS = jsonObjDS.assignTimestampsAndWatermarks(WatermarkStrategy.<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2)).withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
            @Override
            public long extractTimestamp(JSONObject element, long recordTimestamp) {
                return element.getLong("ts");
            }
        }));


        //TODO 4.按照sid分组
        KeyedStream<JSONObject, String> jsonObjBySidDS = jsonObjDSWithWMDS.keyBy(json -> json.getJSONObject("common").getString("sid"));


        //TODO 5.去重sid,并转换为JavaBean对象
        SingleOutputStreamOperator<ChapterPlay> chapterPlayDS = jsonObjBySidDS.map(new RichMapFunction<JSONObject,
                ChapterPlay>() {
            private ValueState<String> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                StateTtlConfig ttlConfig = new StateTtlConfig.Builder(Time.days(1)).build();
                ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("sid-state", String.class);
                stateDescriptor.enableTimeToLive(ttlConfig);
                valueState = getRuntimeContext().getState(stateDescriptor);
            }

            @Override
            public ChapterPlay map(JSONObject value) throws Exception {
                //获取状态
                String lastDt = valueState.value();
                Long ts = value.getLong("ts");
                String curDt = DateFormatUtil.toYmdHms(ts);
                long pc = 0L;

                if (lastDt == null || !lastDt.equals(curDt)) {
                    valueState.update(curDt);
                    pc = 1L;
                }
                return ChapterPlay.builder()
                        .vid(value.getJSONObject("appVideo").getString("video_id"))
                        .userId(value.getJSONObject("common").getString("uid"))
                        .duringSec(value.getJSONObject("appVideo").getLong("play_sec"))
                        .pc(pc)
                        .ts(value.getLong("ts"))
                        .build();
            }
        });
        chapterPlayDS.print("chapterPlayDS-->");
        //6.按照uid keyby 去重
        SingleOutputStreamOperator<ChapterPlay> chapterPlayFlatSidDS = chapterPlayDS.keyBy(ChapterPlay::getUserId).flatMap(new RichFlatMapFunction<ChapterPlay, ChapterPlay>() {
            private ValueState<String> valueState;

            @Override
            public void open(Configuration parameters) throws Exception {
                StateTtlConfig ttlConfig = new StateTtlConfig.Builder(Time.days(1)).build();
                ValueStateDescriptor<String> stateDescriptor = new ValueStateDescriptor<>("uid-state", String.class);
                stateDescriptor.enableTimeToLive(ttlConfig);
                valueState = getRuntimeContext().getState(stateDescriptor);

            }

            @Override
            public void flatMap(ChapterPlay value, Collector<ChapterPlay> out) throws Exception {
                String lastDt = valueState.value();
                Long ts = value.getTs();
                String curDt = DateFormatUtil.toYmdHms(ts);
                long vc = 0L;
                if (lastDt == null || !lastDt.equals(curDt)) {
                    valueState.update(curDt);
                    vc = 1L;

                }
                if (vc == 1L) {
                    out.collect(ChapterPlay.builder()
                            .vid(value.getVid())
                            .userId(value.getUserId())
                            .duringSec(value.getDuringSec())
                            .pc(value.getPc())
                            .vc(vc)
                            .ts(value.getTs())

                            .build());
                }


            }
        });

        chapterPlayFlatSidDS.print("chapterPlayFlatSidDS-->");

        //todo 6.1关联视频维度表拿到章节id
        SingleOutputStreamOperator<ChapterPlay> beanDimDs = AsyncDataStream.unorderedWait(chapterPlayFlatSidDS, new DimAsyncFunction<ChapterPlay>("DIM_VIDEO_INFO") {

            @Override
            public String getkey(ChapterPlay input) throws Exception {
                return input.getVid();
            }

            @Override
            public void join(ChapterPlay input, JSONObject dimInfo) throws Exception {
                input.setChapterId(dimInfo.getString("CHAPTER_ID"));
            }
        }, 60, TimeUnit.SECONDS);


        //todo 6.2 关联章节表拿到章节id.和章节名称
        SingleOutputStreamOperator<ChapterPlay> reduceDS = AsyncDataStream.unorderedWait(beanDimDs,
                new DimAsyncFunction<ChapterPlay>("DIM_CHAPTER_INFO") {
                    @Override
                    public String getkey(ChapterPlay input) throws Exception {
                        return input.getChapterId();
                    }

                    @Override
                    public void join(ChapterPlay input, JSONObject dimInfo) throws Exception {
                        input.setChapterName(dimInfo.getString("CHAPTER_NAME"));
                    }
                }, 60, TimeUnit.SECONDS);

        reduceDS.print("reduceDS-->");

        //TODO 7按照章节id分组
        KeyedStream<ChapterPlay, String> keyedByCid = reduceDS.keyBy(ChapterPlay::getChapterId);

        keyedByCid.print("keyedByCid------->");
        //TODO 8分组开窗聚合

        SingleOutputStreamOperator<ChapterPlay> resultDS =
                keyedByCid.window(TumblingEventTimeWindows.of(org.apache.flink.streaming.api.windowing.time.Time.seconds(10))).reduce(new ReduceFunction<ChapterPlay>() {
                    @Override
                    public ChapterPlay reduce(ChapterPlay value1, ChapterPlay value2) throws Exception {
                        value1.setPc(value1.getPc() + value2.getPc());
                        value1.setVc(value1.getVc() + value2.getVc());
                        value1.setDuringSec(value1.getDuringSec() + value2.getDuringSec());
                        return value1;
                    }
                }, new WindowFunction<ChapterPlay, ChapterPlay, String, TimeWindow>() {
                    @Override
                    public void apply(String s, TimeWindow window, Iterable<ChapterPlay> input, Collector<ChapterPlay> out) throws Exception {
                        WindowFunctionUtil.set(input,window,out);
                    }
                });

        //TODO 9.将数据写出
        resultDS.print("resultDS--->");
        resultDS.addSink(MyClickHouseUtil.getSinkFunction("insert into dws_play_chapter_window values(?,?,?,?,?,?,?,?,?)"));

        //TODO 10.启动任务
        env.execute("Dws161_ChapterPlayViewWindow");

    }
}
